package com.JUC.cha10.sec01;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class MyData {

    ThreadLocal<Integer> threadLocalInt = ThreadLocal.withInitial(() -> 0);

    public void add() {
        threadLocalInt.set(threadLocalInt.get() + 1);
    }

}

/**
 * 【强制】必须回收自定义的ThreadLocal变量，尤其在线程池场景下，线程经常会被复用，如果不清理自定义的ThreadLocal变量，可能会影响后续业务逻辑和造成内存泄露等问题。
 * 尽量在代理中使用try-finally块进行回收
 */
public class ThreadLocalDemo2 {

    public static void main(String[] args) {

        MyData myData = new MyData();
        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        try {
            for (int i = 0; i < 10; i++) {
                threadPool.submit(() -> {
                    try {
                        Integer before = myData.threadLocalInt.get();
                        myData.add();
                        Integer after = myData.threadLocalInt.get();
                        System.out.println(Thread.currentThread().getName() + "线程 \t before：" + before + "\t after：" + after);
                    } finally {
                        myData.threadLocalInt.remove();
                    }
                });
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            threadPool.shutdown();
        }

    }
}
